<template>
  <div>
    <div>
      <form-panel ref="formPanel" :list="fromList" :cols="2" labelWidth="110" :isSubmitBtn="false"></form-panel>
      <el-upload
        style="width:50%"
        action="/api/file/oss/upload"
        :on-preview="this.handlePreview"
        :on-remove="this.handleRemove"
        :before-remove="this.beforeRemove"
        :on-success="this.handleSuccess"
        :on-exceed="handleExceed"
        accept=".jpg,.png,.pdf,.xls,.xlsx,.rar"
        :limit="1"
        :file-list="this.fileList"
        :disabled="newStatus"
      >
        <el-button size="small" type="primary" :disabled="newStatus">点击上传</el-button>
        <div slot="tip" class="el-upload__tip" :disabled="newStatus">附件支持上传excel、PDF、RAR、JPG格式</div>
      </el-upload>
    </div>

    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <AjaxButton type="primary" :disabled="newStatus" :click="saveDialog">保 存</AjaxButton>
      <AjaxButton type="primary" :disabled="submitEnable" :click="submit">提 报</AjaxButton>
      <el-button @click="closeDialog">关 闭</el-button>
    </div>
    <!-- 工单查询 -->
    <BaseDialog :visible.sync="isShowGdcx" title="工单查询" destroyOnClose :containerStyle="{ height: 'calc(100% - 70px)', overflow: 'auto', paddingBottom: '70px' }">
      <WorkSearch @saveDialog="confirmGdcx" @closeDialog="isShowGdcx = false"></WorkSearch>
    </BaseDialog>
  </div>
</template>

<script>
import FormPanel from '../../../../components/FormPanel/FormPanel.vue';
import WorkSearch from './WorkSearch.vue';
import { applyMileageChange } from '@/api/repair/repairBusiness/mileageModify/index.js';
import moment from 'moment';
import SERVER from '@/api/server';
import { getConfigHeaders } from '@/api/fetch';
import axios from '@/api/fetch';
export default {
  components: { FormPanel, WorkSearch },
  props: ['row', 'type'],
  data() {
    return {
      fromList: this.createFromList(),
      changeId: undefined,
      isShowGdcx: false,
      fileList: [],
      getConfigHeaders: getConfigHeaders,
      ownerNo: '',
      newStatus: false
    };
  },
  computed: {
    submitEnable() {
      return !!!this.fromList.find(x => x.fieldName === 'changeNo').initialValue;
    }
  },
  mounted() {
    if (this.type == 'edit') {
      this.fromList.forEach(x => {
        x.initialValue = this.row[x.fieldName];
      });
      if (this.row.url) {
        this.fileList.push({ name: this.row.name, url: this.row.url });
      }
      this.changeId = this.row.changeId;
    }
  },
  methods: {
    createFromList() {
      return [
        {
          type: 'INPUT',
          label: '里程变更申请单号',
          fieldName: 'changeId',
          disabled: true,
          hidden: true,
          initialValue: undefined
        },
        {
          type: 'INPUT',
          label: '里程变更申请单号',
          fieldName: 'changeNo',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '关联工单号',
          fieldName: 'roNo',
          readonly: true,
          disabled: this.type == 'edit',
          rules: [{ required: true, message: '请输入', trigger: 'blur' }],
          unitRender: () => {
            return <el-button icon="el-icon-search" onClick={() => (this.isShowGdcx = true)}></el-button>;
          }
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license',
          disabled: true
        },
        {
          type: 'DATE',
          label: '申请时间',
          fieldName: 'changeDate',
          dateFormat: 'yyyy-MM-dd HH:mm:ss',
          dateType: 'datetime',
          initialValue: moment().format('YYYY-MM-DD HH:mm:ss'),
          disabled: true
        },
        {
          type: 'INPUT',
          label: '车主姓名',
          fieldName: 'ownerName',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '当前里程数',
          fieldName: 'beforeMileage',
          disabled: true,
          initialValue: 0
        },
        {
          type: 'INPUT_NUMBER',
          label: '变更里程数',
          fieldName: 'afterMileage',
          precision: 2,
          disabled: false,
          rules: [{ required: true, message: '请输入', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '申请原因',
          fieldName: 'remark',
          disabled: false,
          maxlength: 45
        }
        // {
        //   type: 'UPLOAD_FILE',
        //   label: '上传文件',
        //   fieldName: 'file',
        //   placeholder: '上传文件...',
        //   selfCols: 2,
        //   // rules: [{ required: true, message: '请上传文件', trigger: 'change' }],
        //   initialValue: [],
        //   upload: {
        //     actionUrl: '/api/dmscloud.repair/changeMileage/importFile',
        //     limit: 1,
        //     fileTypes: ['jpg', 'png', 'pdf', 'rar', 'xls', 'xlsx'],
        //     onPreview: this.handlePreview
        //   }
        // }
        // {
        //   type: 'INPUT',
        //   label: '上传文件',
        //   fieldName: 'file',
        //   render: () => {
        //     return (
        //       <el-upload
        //         class="upload-demo"
        //         ref="upload"
        //         headers={getConfigHeaders()}
        //         action="/api/dmscloud.repair/changeMileage/importFile"
        //         on-preview={this.handlePreview}
        //         on-remove={this.handleRemove}
        //         on-success={this.handleSuccess}
        //         on-error={this.handleError}
        //         on-change={this.handleChange}
        //         limit={2}
        //         file-list={this.fileList}
        //         before-remove={this.beforeRemove}
        //         with-credentials={true}
        //       >
        //         <el-button size="small" type="primary">
        //           点击上传
        //         </el-button>
        //         <span class="el-upload__tip">只能上传'jpg,png'文件，且不超过</span>
        //       </el-upload>
        //     );
        //   }
        // }
      ];
    },
    handleExceed() {
      this.$notify.warning(`只能上传1个附件。如需更新附件，请先删除之前上传的附件`);
    },

    handleSuccess(response, file, fileList) {
      if (response.data) {
        this.fileList.push({ name: file.name, url: response.data });
        this.$notify.success({ title: '提示信息', message: '附件上传成功！！！' });
      } else {
        this.fileList = [];
        this.$notify.error({ title: '提示信息', message: '附件上传失败！！！' });
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.fileList = [];
    },
    handlePreview(file) {
      let fullUrl = file.url;
      const downloadElement = document.createElement('a');
      downloadElement.style.display = 'none';
      downloadElement.href = fullUrl;
      downloadElement.download = file.name; //下载后文件名
      document.body.appendChild(downloadElement);
      downloadElement.click(); //点击下载
      document.body.removeChild(downloadElement); //下载完成移除元素

      // axios.get(fullUrl, { responseType: 'blob' }).then(res => {
      //   if (!res) {
      //     this.$message.error('下载模板文件失败');
      //     return false;
      //   }
      //   const blob = res.data;
      //   const href = window.URL.createObjectURL(blob);
      //   const downloadElement = document.createElement('a');
      //   downloadElement.style.display = 'none';
      //   downloadElement.href = href;
      //   downloadElement.download = file.name; //下载后文件名
      //   document.body.appendChild(downloadElement);
      //   downloadElement.click(); //点击下载
      //   document.body.removeChild(downloadElement); //下载完成移除元素
      //   window.URL.revokeObjectURL(href); //释放掉blob对象
      // });
      // axios
      //   .get(file.url, { responseType: 'blob' })
      //   .then(res => {})
      //   .catch(err => {
      //     console.log(err);
      //   });
      // var a = document.createElement('a');
      // var event = new MouseEvent('click');
      // a.download = file.name;
      // a.href = file.url;
      // a.dispatchEvent(event);
      // console.log(file);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    async saveDialog(type) {
      const [err, data] = await this.$refs.formPanel.GET_FORM_DATA();
      if (err) return;
      data.ownerNo = this.ownerNo;
      if (type === 'submit') {
        data.changeId = this.changeId;
        data.status = 99931002; // 提报
      } else {
        data.changeId = this.changeId;
        data.status = this.type === 'add' ? 99931001 : this.row.status; // 保存
      }
      console.log(this.fileList, 'this.fileList');
      if (this.fileList.length) {
        data.fileName = this.fileList[0].name;
        data.fileAddr = this.fileList[0].url;
      }
      let res = await applyMileageChange(data);
      if (res.resultCode === 200) {
        // 回写里程变更申请单号
        this.fromList.find(x => x.fieldName === 'changeNo').initialValue = res.data.changeNo;
        this.changeId = res.data.changeId;
        if (type === 'submit') {
          this.$notify.success({ type: '提示信息', message: '提报成功!!' });
          this.$emit('close');
        } else {
          this.$notify.success({ type: '提示信息', message: '保存成功!!' });
          this.fromList.forEach(x => (x.disabled = true));
          this.newStatus = true;
          this.$emit('saveDialog');
        }
      }
    },
    // 提报
    submit() {
      this.saveDialog('submit'); //
    },
    closeDialog(param) {
      this.$emit('close');
    },

    confirmGdcx([param]) {
      this.isShowGdcx = false;
      this.fromList.find(x => x.fieldName === 'roNo').initialValue = param['RO_NO'];
      this.fromList.find(x => x.fieldName === 'vin').initialValue = param['VIN'];
      this.fromList.find(x => x.fieldName === 'license').initialValue = param['LICENSE'];
      this.fromList.find(x => x.fieldName === 'ownerName').initialValue = param['OWNER_NAME'];
      this.ownerNo = param['OWNER_NO'];
      this.fromList.find(x => x.fieldName === 'beforeMileage').initialValue = param['MILEAGE'];
    }
  }
};
</script>
